import { Component, OnInit } from '@angular/core'
import { Router, NavigationEnd } from '@angular/router'
import { Location } from '@angular/common'
import { Toast } from 'ng-zorro-antd-mobile'
import { CommonUtil } from './common/utils/common.util'
import { CoolLocalStorage } from './common/coolStorage/cool-local-storage'

declare var cordova: any
declare var navigator: any
declare var StatusBar: any

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  providers: [Toast]
})
export class AppComponent implements OnInit {
  constructor(
    private router: Router,
    private location: Location,
    private toast: Toast,
    private utils: CommonUtil,
    private storage: CoolLocalStorage
  ) {
    router.events.forEach(e => {
      if (e instanceof NavigationEnd) {
        window.scrollTo(0, 0)
      }
    })
  }

  ngOnInit() {
    document.addEventListener('deviceready', this.onDeviceReady.bind(this), false)
  }
  onDeviceReady() {
    this.storage.setItem('platformId', cordova.platformId)
    // 注册返回按钮事件
    document.addEventListener('backbutton', this.onBackKeyDown.bind(this), false)
    // 设置状态栏沉浸
    if (cordova.platformId === 'android') {
      StatusBar.backgroundColorByHexString('#ffffff')
      StatusBar.styleDefault()
    }
    // 获取APP版本号
    cordova.getAppVersion.getVersionNumber(version => {
      this.storage.setItem('appVersion', version)
    })
  }
  // 返回按钮
  onBackKeyDown() {
    let url = this.router.url
    let whitelist = [
      '/workspace/home/index',
      '/workspace/discover/index',
      '/workspace/follow/index',
      '/workspace/mine/index'
    ]
    // 如果在tab页下
    if (whitelist.indexOf(url) > -1) {
      this.utils.info('再按一次退出')
      document.removeEventListener('backbutton', this.onBackKeyDown, false)
      document.addEventListener('backbutton', this.exitApp, false)
      // 3秒后重新注册
      let intervalID = window.setTimeout(function() {
        window.clearTimeout(intervalID)
        document.removeEventListener('backbutton', this.exitApp, false)
        document.addEventListener('backbutton', this.onBackKeyDown, false)
      }, 3000)
    } else {
      this.location.back()
    }
  }
  // 退出APP
  exitApp() {
    navigator.app.exitApp()
  }
}
